import {Component, EventEmitter, Inject, Injector, Input, OnDestroy, OnInit, Output} from '@angular/core';
import {BaseMapComponent} from '../../base-map/base-map.component';
import {SbVectorLayer} from '../../bean/SbVectorLayer';
import Feature from 'ol/Feature';
import Layer from 'ol/layer/Layer';
import MapBrowserEvent from 'ol/MapBrowserEvent';
import {NzMessageService} from 'ng-zorro-antd';
import {map} from 'rxjs/operators';
import {FeatureClickEvent} from '../../bean/ISbBaseLayer';

@Component({
    template: ``,
    selector: 'vector-layer'
})
export class VectorLayerComponent implements OnInit, OnDestroy {

    @Output() featureClick = new EventEmitter<FeatureClickEvent>();
    vectorLayer: SbVectorLayer;
    private _init = false;

    constructor(
        private message: NzMessageService,
        @Inject(BaseMapComponent) public readonly baseMap?: BaseMapComponent,
        @Inject(Injector) public readonly inject?: Injector) {
    }

    private _layerId;

    get layerId() {
        return this._layerId;
    }

    @Input()
    set layerId(value) {
        if (!this._init) {
            this._layerId = value;
        }
    }

    private _visible = false;

    get visible(): boolean {
        return this._visible;
    }

    @Input()
    set visible(value: boolean) {
        this._visible = value;
        if (this.vectorLayer) {
            this.vectorLayer.setVisible(value);
        }
    }

    ngOnInit() {
        if (!this.layerId) {
            this.message.info('图层标识不允许为空！');
        }

        // 成功初始化
        this._init = true;

        this.vectorLayer = new SbVectorLayer({
            layerId: this.layerId,
            featureClickCallback: this.featureClickCallback.bind(this),
            visible: this.visible
        }, this.inject);

        this.baseMap.map.addLayer(this.vectorLayer);
    }

    featureClickCallback(feature: Feature, layer: Layer, mapEvent: MapBrowserEvent) {
        // this.message.info("图层要素点击！");
        this.featureClick.emit({
            feature: feature,
            layer: layer,
            mapEvent: mapEvent
        });
    }

    ngOnDestroy(): void {
        if (this.baseMap && this.vectorLayer) {
            this.baseMap.map.removeLayer(this.vectorLayer);
        }
    }
}
